<?php


namespace app\index\controller;


use app\index\common\Common;
use app\index\model\ActionRole;
use app\index\model\Country;
use app\index\model\Customer;
use app\index\model\CustomerDiscount;
use app\index\model\CustomerDiscountHistory;
use app\index\model\CustomerOrder;
use app\index\model\CustomerOrderDetail;
use app\index\model\CustomerTrackRecord;
use app\index\model\Group;
use app\index\model\Member;
use app\index\model\MemberCostHistory;
use app\index\model\Product;
use app\index\model\Tags;
use app\index\model\User;
use think\Exception;
use think\Loader;
use think\Request;
use think\response\Json;

class CustomerController extends BaseController
{

    protected $request;
    protected $validate;
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->request=$request;
        $this->validate=Loader::validate('Customer');
    }

    public function getParam(){
        $tags=Tags::getTagsList();
        $country=Country::getCountryList();
        $track_type=CustomerTrackRecord::$track_type;
        ['user_list'=>$user_list,'group_list'=>$group_list]=User::getUserList();

        return json(['code'=>0,'tag'=>$tags,'country'=>$country,'user_list'=>$user_list,'group_list'=>$group_list,'track_type'=>$track_type]);
    }

    public function getList(){
        $page=input('post.pageIndex',1);
        $size=input('post.pageSize',10);
        $post=input('post.',[]);
        $search_param=[
            'search_key'=>$post['search_key']??null,
            'search_value'=>$post['search_value']??null,
            'tags'=>$post['tags']??null,
            'group_id'=>$post['group_id']??null,
            'user_id'=>$post['user_id']??null,
            'create_time'=>$post['create_time']??null,
            'customer_id'=>$post['customer_id']??null,
            'type'=>$post['type']??null,
            'order_by'=>$post['order_by']??'id',
            'sort_by'=>$post['sort_by']??'asc',
        ];
        $page_param=[
            'page_num'=>$page,
            'page_size'=>$size,
        ];
        ['status'=>$status,'result'=>$result]=Customer::getCustomerList($search_param,$page_param);
        if($status===false){
            return json(['code'=>1,'msg'=>$result['msg']]);
        }
        return json(['code'=>0,'data'=>$result['data'],'pageTotal'=>$result['total'],'action_role'=>$result['action_role']]);
    }

    public function getCustomerListByName(){
        $name=input('post.name');
        $group=input('post.group');
        if(!$name){
            return json(['code'=>0,'data'=>[]]);
        }
        ['status'=>$status,'result'=>$result]=Customer::getCustomerListByName($name,$group);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'data'=>$result['data']]);
    }

    public function getCustomerByName(){
        $name=input('post.name');
        $group=input('post.group');
        if(!$name){
            return json(['code'=>0,'data'=>[]]);
        }
        ['status'=>$status,'result'=>$result]=Customer::getCustomerByName($name,$group);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'data'=>$result['data']]);
    }

    public function getCustomerFixedTags(){
        $CustomerClass=new Customer();
        $fixed_tags=$CustomerClass->fixed_tags;
        return json(['code'=>0,'fixed_tags'=>$fixed_tags]);
    }

    public function getCustomerById(){
        $id=input('post.id');
        if(!$id){
            return json(['code'=>1,'msg'=>'id 不能为空']);
        }
        ['status'=>$status,'result'=>$result]=Customer::getCustomerById($id);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'data'=>$result['data'],'tags'=>$result['tags']]);
    }

    public function getCustomerOrderParam(){
        $group_list=Group::getGroupList();

        ['action_role'=>$action_role]=ActionRole::checkUserActionRole('customer');

        return json(['code'=>0,'group_list'=>$group_list,'action_role'=>$action_role]);
    }

    /**
     * createOrder
     * 客户下单
     * @url customer/order/create
     * @method POST
     * @return Json
     * @author Asira
     * @date 2021/2/2
     */
    public function createOrder(): Json
    {
        $data=input('post.data/a');
        $validate_result=$this->validate->scene('customer_order')->check($data);
        if(!$validate_result){
            return json(['code'=>1,'msg'=>$this->validate->getError()],200);
        }
        $pack_product=[];
        $pro_id[]=$data['id'];
        if ($data['id'] === 0 && $data['detail_name']) {
            $pro_id = [];
            foreach ($data['detail_name'] as $key => $value) {
                if ($value['delete'] === false) {
                    $validate_result = $this->validate->scene('customer_order_product')->check($value);
                    if (!$validate_result) {
                        return json(['code' => 1, 'msg' => $this->validate->getError()], 200);
                    }
                    $pack_product[] = [
                        'en_name' => $value['en_name'],
                        'cn_name' => $value['cn_name'],
                        'remark' => $value['remark'] ?? '',
                        'type' => $value['type'],
                        'weight' => $value['weight'],
                        'amount' => $value['amount'],
                        'pro_id' => $value['id']
                    ];
                    $pro_id[] = $value['id'];
                }
            }
        }
        $insert_data=[
            'pro_id'=>$data['id'],
            'cn_name'=>$data['cn_name'],
            'en_name'=>$data['en_name'],
            'remark'=>$data['remark']??'',
            'gift'=>$data['gift']??0,
            'pro_type'=>$data['type'],
            'amount'=>$data['amount'],
            'weight'=>$data['weight'],
            'selling_price'=>$data['selling_price'],
            'customer_name'=>trim($data['customer_name']),
            'create_user'=>$this->user_session['id'],
            'create_group'=>$data['group'],
        ];

        ['status'=>$status,'result'=>$result]=CustomerOrder::createOrder($insert_data,$pack_product,$pro_id);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'msg'=>$result]);
    }

    public function createOrderBatch(){
        $data=input('post.data/a');

        $validate_result=$this->validate->scene('customer_order_batch')->check($data);

        if(!$validate_result){
            return json(['code'=>1,'msg'=>$this->validate->getError()],200);
        }

        $CustomerClass = new Customer();
        $CustomerOrderClass = new CustomerOrder();
        $CustomerOrderDetailClass=new CustomerOrderDetail();
        $ProductClass=new Product();

        $customer_id=$CustomerClass::checkCustomer($data['customer_name'],$data['group']);
        $insert_data=[];
        $children=[];
        $pro_id=[];
        foreach ($data['product'] as $key=>$value){
            $validate_result=$this->validate->scene('customer_order_batch_product')->check($value);

            if(!$validate_result){
                return json(['code'=>1,'msg'=>$this->validate->getError()],200);
            }

            if($value['pro_id']===0){
                if(!empty($value['children'])){
                    foreach ($value['children'] as $item) {
                        $pro_id[]=$item['pro_id'];
                        if(!$item['pro_id']){
                            return json(['code'=>1,'msg'=>'商品详情的商品必须已存在']);
                        }
                        if(!is_numeric($item['amount'])){
                            return json(['code'=>1,'msg'=>'商品详情的数量必须为数字']);
                        }
                        $children[$key][] = [
                            'en_name' => $item['en_name'],
                            'cn_name' => $item['cn_name'],
                            'remark' => $item['remark']??'',
                            'type' => $item['type'],
                            'weight' => $item['weight'],
                            'amount' => $item['amount'],
                            'pro_id' => $item['pro_id']
                        ];
                    }
                }/*else{
                    return json(['code'=>1,'msg'=>'商品详情不能为空']);
                }*/
            }else{
                $pro_id[]=$value['pro_id'];
            }

            $insert_data[$key]=[
                'pro_id'=>$value['pro_id'],
                'cn_name'=>$value['cn_name'],
                'en_name'=>$value['en_name'],
                'gift'=>$value['gift']??0,
                'pro_type'=>$value['type'],
                'amount'=>$value['amount'],
                'weight'=>$value['weight'],
                'remark'=>$value['remark']??'',
                'selling_price'=>$value['selling_price'],
                'customer_name'=>$customer_id,
                'create_user'=>$this->user_session['id'],
                'create_group'=>$data['group'],
            ];
        }
        $CustomerOrderClass->startTrans();
        try {
            $stock_list=$ProductClass->where('id','in',$pro_id)->where('del_flag',0)->lock(true)->column('amount,demand_stock,locked_demand_stock,type','id');
            foreach ($insert_data as $key=>$value){
                if($value['pro_id']) {
                    $arr =& $stock_list[$value['pro_id']];
                    ['demand_stock' => $demand_stock, 'stock_demand_stock' => $stock_demand_stock,'stock_locked_demand_stock'=>$stock_locked_demand_stock] = Common::demandStock($arr, $value['amount']);
                    $insert_data[$key]['demand_stock'] = $demand_stock;
                    $arr['demand_stock'] = $stock_demand_stock;
                    $arr['locked_demand_stock'] = $stock_locked_demand_stock;
                }
            }
            $result = $CustomerOrderClass->saveAll($insert_data, false);
            if ($result === false) {
                throw Exception('下单失败');
            }
            $insert_children=[];
            foreach ($result as $key => $value) {
                if (isset($children[$key])) {
                    foreach ($children[$key] as $i => $item) {
                        $arr=&$stock_list[$item['pro_id']];
                        ['demand_stock'=>$demand_stock,'stock_demand_stock'=>$stock_demand_stock,'stock_locked_demand_stock'=>$stock_locked_demand_stock]=Common::demandStock($arr,$item['amount']);
                        $item['demand_stock']=$demand_stock;
                        $arr['demand_stock']=$stock_demand_stock;
                        $arr['locked_demand_stock'] = $stock_locked_demand_stock;
                        $item['customer_order_id'] = $value['id'];
                        $insert_children[] = $item;
                    }
                }
            }

            if (!empty($insert_children)) {
                $result = $CustomerOrderDetailClass->saveAll($insert_children);
                if ($result === false) {
                    throw Exception('保存商品详情失败');
                }
            }

            $result = $ProductClass->allowField(['id','demand_stock','locked_demand_stock'])->isUpdate(true)->saveAll($stock_list);
            if($result===false){
                throw Exception('保存库存失败');
            }

            $CustomerOrderClass->commit();
            return json(['code'=>0,'msg'=>'下单成功']);
        }catch (Exception $e){
            $CustomerOrderClass->rollback();
            trace('createOrderBatch 下单失败'.$e->getMessage(),'error');
            return json(['code'=>1,'msg'=>'下单失败'.$e->getMessage()]);
        }
    }

    public function cancelCustomerOrder(){
        $id=input('post.id');
        if(!$id){
            return json(['code'=>1,'msg'=>'id 不能为空']);
        }
        ['status'=>$status,'result'=>$result]=CustomerOrder::cancelCustomerOrder($id);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'msg'=>$result]);
    }

    public function updateCustomerOrder(){
        $data=input('post.data/a',[]);
        $validate_result=$this->validate->scene('customer_order_update')->check($data);

        if(!$validate_result){
            return json(['code'=>1,'msg'=>$this->validate->getError()],200);
        }
        $pack_product=[];
        $pro_id[]=$data['id'];
        if($data['id']===0 && $data['detail_name']){
            /*if(empty($data['detail_name'])){
                return json(['code'=>1,'msg'=>'详细信息不能为空'],200);
            }*/
            $pro_id=[];
            foreach ($data['detail_name'] as $key=>$value){
                $validate_result=$this->validate->scene('customer_order_product')->check($value);
                if(!$validate_result){
                    return json(['code'=>1,'msg'=>$this->validate->getError()],200);
                }
                $pro_id[]=$value['id'];
                $pack_product[] = [
                    'customer_order_id'=>$data['order_id'],
                    'id' => $value['customer_order_detail_id'],
                    'en_name' => $value['en_name'],
                    'cn_name' => $value['cn_name'],
                    'remark' => $value['remark']??'',
                    'type' => $value['type'],
                    'weight' => $value['weight'],
                    'amount' => $value['amount'],
                    'pro_id' => $value['id'],
                    'delete'=>$value['delete'],
                ];
            }
        }
        $update_data=[
            'pro_id'=>$data['id'],
            'cn_name'=>$data['cn_name'],
            'en_name'=>$data['en_name'],
            'remark'=>$data['remark']??'',
            'pro_type'=>$data['type'],
            'amount'=>$data['amount'],
            'weight'=>$data['weight'],
            'selling_price'=>$data['selling_price'],
            'customer_name'=>$data['customer_name'],
            'gift'=>$data['gift']??0,
        ];
        ['status'=>$status,'result'=>$result]=CustomerOrder::updateOrder($data['order_id'],$update_data,$pack_product,$pro_id);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        ['status'=>$status,'result'=>$result]=Product::demandStockByProduct($pro_id);
        if($status===false){
            return json(['code'=>2,'msg'=>'更新订单成功，锁定需求库存失败',$result]);
        }
        return json(['code'=>0,'msg'=>'更新订单成功']);
    }

    public function createCustomer(){
        $data=input('post.data/a');
        $validate_result=$this->validate->scene('create')->check($data);
        if(!$validate_result){
            return json(['code'=>1,'msg'=>$this->validate->getError()],200);
        }
        ['status'=>$status,'result'=>$result]=Customer::getCustomerByName($data['nick_name'],$data['group']);
        if($status===true){
            return json(['code'=>1,'msg'=>'客户名称已被使用']);
        }
        $tags=$data['tags'];
        $insert_data=[
            'customer_name'=>trim($data['customer_name']),
            'nick_name'=>trim($data['nick_name']),
            'email'=>$data['email'],
            'ship_fee'=>$data['ship_fee'],
            'country'=>$data['country'],
            'city'=>$data['city'],
            'address'=>$data['address'],
            'home_page'=>$data['home_page'],
            'zip_code'=>$data['zip_code'],
            'phone'=>$data['phone'],
            'remark'=>$data['remark']??'',
            'birthday'=>$data['birthday']??null,
            'create_user'=>$this->user_session['id'],
            'create_group'=>$data['group'],
        ];

        ['status'=>$status,'result'=>$result]=Customer::createCustomer($insert_data,$tags);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'msg'=>$result]);
    }

    public function updateCustomer(){
        $data=input('post.data/a');
        $validate_result=$this->validate->scene('update')->check($data);
        if(!$validate_result){
            return json(['code'=>1,'msg'=>$this->validate->getError()],200);
        }
        $tags=$data['tags'];
        $update_data=[
            'customer_name'=>trim($data['customer_name']),
            'nick_name'=>trim($data['nick_name']),
            'ins_name'=>trim($data['ins_name']),
            'other_name'=>trim($data['other_name']),
            'email'=>$data['email'],
            'ship_fee'=>$data['ship_fee'],
            'country'=>$data['country'],
            'city'=>$data['city'],
            'address'=>$data['address'],
            'home_page'=>$data['home_page'],
            'zip_code'=>$data['zip_code'],
            'phone'=>$data['phone'],
            'remark'=>$data['remark']??'',
            'birthday'=>$data['birthday']??null,
        ];

        ['status'=>$status,'result'=>$result]=Customer::updateCustomer($data['id'],$update_data,$tags);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'msg'=>$result]);
    }

    public function getMemberById(){
        $id=input('post.id');
        $result=Member::getMemberByCustomerId($id);
        return json(['code'=>0,'data'=>$result]);
    }

    public function addMember()
    {
        $data=input('post.data/a');
        if (/*!$data['card_id']||*/!$data['type']){
            return json(['code'=>1,'msg'=>'请填写会员账号和会员类型']);
        }
        if (!isset($data['num'])||!$data['num']){
            $data['num']=0;
        }
        if (!isset($data['sendNum'])||!$data['sendNum']){
            $data['sendNum']=0;
        }
        ['status'=>$status,'result'=>$result]=Member::addMember($data);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'msg'=>$result]);
    }

    public function updateMember()
    {
        $data=input('post.data/a');
/*        var_dump($data);
        die();*/
        if (!isset($data['num'])){
            return json(['code'=>1,'msg'=>'请输入充值金额']);
        }
        if(!is_numeric($data['num'])){
            return json(['code'=>1,'msg'=>'输入的充值金额不对']);
        }
        if (!isset($data['sendNum'])||!$data['sendNum']){
            $data['sendNum']=0;
        }
        ['status'=>$status,'result'=>$result]=Member::updateMember($data);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'msg'=>$result]);
    }

    public function getRecordById()
    {
        $page=input('post.pageIndex',1);
        $size=input('post.pageSize',30);
        $post=input('post.');
        $search_param=[
            'type'=>$post['type']??null,
            'id'=>$post['id']??null,
        ];
        $page_param=[
            'page_num'=>$page,
            'page_size'=>$size,
        ];
        ['status'=>$status,'result'=>$result]=MemberCostHistory::getRecordById($search_param,$page_param);
        if ($status==false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'data'=>$result['data'],'pageTotal'=>$result['total'],'customer_data'=>$result['customer_data'],'type_list'=>$result['type_list']]);
    }

    public function getEmail()
    {
        $name=input('post.name');
        $id=input('post.id');
        ['status'=>$status,'result'=>$result]=Customer::getEmailByName($name,$id);
        if ($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'data'=>$result['data'],'tags'=>$result['tags']]);
    }

    public function mergeCustomer()
    {
        $ids=input('post.ids/a');
        if (count($ids)<2){
            return json(['code'=>1,'msg'=>'请选择至少两个客户']);
        }
        ['status'=>$status,'result'=>$result]=Customer::mergeCustomer($ids);
        if($status==0){
            return json(['code'=>0,'msg'=>$result]);
        }
        if ($status==2){
            return json(['code'=>2,'data'=>$result]);
        }
        return json(['code'=>1,'msg'=>$result]);
    }

    public function chooseMerge()
    {
        $row=input('post.row/a');
        $table=input('post.table/a');
        if (empty($row)){
            return json(['code'=>1,'msg'=>'请选择']);
        }
        $id=$row['id'];
        $ids=[];
        foreach($table as $k=>$v){
            if ($v['id']!==$id){
                $ids[]=$v['id'];
            }
        }
        ['status'=>$status,'result'=>$result]=Customer::chooseMerge($ids,$id);
        if($status==false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'msg'=>$result]);
    }

    public function trackRecord(){
        $id=input('post.id');
        if(empty($id)){
            return json(['code'=>1,'msg'=>'id不能为空']);
        }
        $track_record=CustomerTrackRecord::getByCustomerId($id);
        $addTrack=true;
        foreach ($track_record as $key=>$value){
            if($value['status']===0) {
                $addTrack = false;
                break;
            }
        }
        return json(['code'=>0,'data'=>$track_record,'addTrack'=>$addTrack]);
    }

    public function addTrackRecord(){
        $id=input('post.id');
        $data=input('post.data/a');
        $end_id=input('post.end_id');
        if(empty($data['content'])){
            return json(['code'=>1,'msg'=>'填写跟进内容']);
        }
        $track_record=[
            'order_id'=>$id,
            'content'=>$data['content'],
            'appointment_time'=>$data['appointment_time']?:null,
            'create_user'=>$this->user_session['id'],
        ];

        if($end_id){
            if(!$track_record['appointment_time']){
                return json(['code'=>1,'msg'=>'请选择预约时间']);
            }
        }

        $customer['last_track_time']= $data['appointment_time'] ?: date('Y-m-d H:i:s');
        ['status'=>$status,'result'=>$result]=CustomerTrackRecord::addTrackRecord($id,$track_record,$customer,$end_id);
        if($status){
            return json(['code'=>0,'msg'=>$result]);
        }
        return json(['code'=>1,'msg'=>$result]);
    }

    public function endTrackRecord(){
        $id=input('post.id');
        $order_id=input('post.order_id');
        ['status'=>$status,'result'=>$result]=CustomerTrackRecord::endTrackRecord($id,$order_id);
        if($status){
            return json(['code'=>0,'msg'=>$result]);
        }
        return json(['code'=>1,'msg'=>$result]);
    }

    public function endsTrackRecord(){
        $ids=input('post.ids/a');
        ['status'=>$status,'result'=>$result]=CustomerTrackRecord::endsTrackRecord($ids);
        if($status){
            return json(['code'=>0,'msg'=>$result]);
        }
        return json(['code'=>1,'msg'=>$result]);
    }

    public function customerHomeData(){
        $customer=new \app\websocket\model\Customer();
        $consumption_data=$customer::customerConsumption($this->user_session['id']);
        if($consumption_data===false) {
            return json(['code'=>1,'msg'=>'客户数据获取失败']);
        }
        $birthday_data=$customer::customerBirthday($this->user_session['id']);
        if($birthday_data===false) {
            return json(['code'=>1,'msg'=>'客户数据获取失败']);
        }
        return json(['code'=>0,'consumption_data'=>$consumption_data,'birthday_data'=>$birthday_data]);
    }

    public function getDiscountById(){
        $id=input('post.id');
        ['status'=>$status,'result'=>$result]=CustomerDiscount::getDiscountBYCustomerId($id);
        return json(['code'=>0,'data'=>$result['data'],'history'=>$result['history']]);
    }

    public function saveDiscount(){
        $data=input('post.');
        if(empty($data['remark'])){
            return json(['code'=>1,'msg'=>'请输入备注']);
        }
        if(!is_numeric($data['balance'])){
            return json(['code'=>1,'msg'=>'请输入金额']);
        }
        $CustomerDiscountClass=new CustomerDiscount();
        $CustomerDiscountHistoryClass=new CustomerDiscountHistory();
        $check=false;
        $customer_data=['balance'=>round($data['balance']+$data['price'],2),'customer_id'=>$data['customer_id']];
        if($data['id']){
            $check=true;
            $customer_data['id']=$data['id'];
        }
        $CustomerDiscountClass->startTrans();
        try {
            $result = $CustomerDiscountClass->isUpdate($check)->save($customer_data);
            if ($result === false) {
                return json(['code' => 1, 'msg' => '保存抵扣失败']);
            }
            $discount_id = $CustomerDiscountClass->id;
            $history_data = ['discount_id' => $discount_id, 'customer_id' => $data['customer_id'], 'price' => $data['price'], 'type' => 1,'create_user'=>$this->user_session['id'],'remark'=>$data['remark']];
            $result=$CustomerDiscountHistoryClass->insert($history_data);
            if ($result === false) {
                return json(['code' => 1, 'msg' => '保存抵扣失败']);
            }
            $CustomerDiscountClass->commit();
            return json(['code'=>0,'msg'=>'保存抵扣成功']);
        }catch (Exception $e){
            $CustomerDiscountClass->rollback();
            trace('save discount error '.$e->getMessage(),'error');
            return json(['code'=>1,'msg'=>'保存抵扣失败']);
        }
    }
}